package org.itboys.mobile.service.pos;

import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.kitchen.dao.order.KitchenOrderMapper;
import org.itboys.kitchen.dao.order.KitchenOrderProductMapper;
import org.itboys.kitchen.entity.mysql.order.KitchenOrder;
import org.itboys.kitchen.entity.mysql.order.KitchenOrderProduct;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.pos.PosResult;
import org.itboys.mobile.entity.pos.PosResult1;
import org.itboys.mobile.entity.pos.order.PosOrder;
import org.itboys.mobile.entity.pos.order.PosOrderProduct;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mobile.service.pos.util.PosHttpHelper;
import org.itboys.mobile.service.pos.util.PosMD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2016年8月10日
 * 联系方式 ：empty90911@126.com
 * 描述：导入POS订单
 */
@Service
public class PosOrderService {
	protected  Logger logger = LoggerFactory.getLogger(getClass());


	@Autowired
	private KitchenOrderMapper orderMapper;
	@Autowired
	private KitchenOrderProductMapper orderProductMapper;
	@Autowired
	private SundayMemberService memberService;

	/**
	 * 推送订单到天街POS。多次推送。知道成功
	 * @param orderId
	 */
   public  void  processOrderToPos(Long orderId){
	   KitchenOrder order =orderMapper.find(orderId);
	   SundayMember shop = memberService.getById(order.getShopId());
	   String remark ="花果山订单";
	   String branchCode=shop.getNumber();
	   Map<String,Object> param = new HashMap<String,Object>();
	   param.clear();
	   param.put("orderId",order.getId());
	   List<KitchenOrderProduct> orderProducts= orderProductMapper.select(param);


		param.clear();
		param.put("Method", "OrderImport");
		//时间搓
		Long timeStamp=new Date().getTime();
		param.put("TimeStamp", timeStamp);


		PosOrder posOrder= new PosOrder();
		posOrder.OrderNo=order.getOrderNo();
		posOrder.OrderType="WS";
		posOrder.OrderDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		posOrder.SellBranch=branchCode;
		posOrder.DeliveryBranch=branchCode;
		posOrder.OriOrderAmt=order.getTotalAmount();
		posOrder.OrderAmt=order.getTotalAmount();
		posOrder.PayableAmt=order.getPayAmount();
		posOrder.CustId=String.valueOf(order.getMemberId());
		posOrder.CustName=order.getReceiveName();
		posOrder.CustPhone=order.getReceiveMobile();
		posOrder.DeliveryAddress=order.getReceiveAddress();
		posOrder.Status=0;
		posOrder.DeliveryPeriod="10:00-11:00";
		posOrder.Remark=remark;
		List<PosOrderProduct> posOrderProducts = new ArrayList<PosOrderProduct>();

	   for(int i =0;i<orderProducts.size();i++){
		   KitchenOrderProduct  orderProduct = orderProducts.get(i);
		   PosOrderProduct posOrderProduct = new PosOrderProduct();
		   posOrderProduct.LineNo=i+1;
		   //posOrderProduct.ItemCode=orderProduct.getProductNo();
		   //2016年9月8日
		   posOrderProduct.ItemCode=orderProduct.getItemCode();
		   posOrderProduct.OriPrice=orderProduct.getPrice();
		   posOrderProduct.SalePrice=orderProduct.getPrice();
		   posOrderProduct.Qty=orderProduct.getNum();
		   posOrderProduct.SaleAmt=orderProduct.getPrice().multiply(new BigDecimal(orderProduct.getNum()));
		   posOrderProduct.Remark="";
		   posOrderProducts.add(posOrderProduct);
	   }
	   String OrderMaster = JsonUtils.objectToString(posOrder);
	   String OrderDetails=JsonUtils.objectToString(posOrderProducts);
	   String data = "{\"OrderMaster\":" +OrderMaster +",\"OrderDetails\":" + OrderDetails +"}";
	   logger.info("订单导入POST:data＝"+data);

	   //logger.info("订单带入POST:签名参数＝"+SignatureParam);
	   String Signature = PosMD5Util.MD5(PosCommons.token+timeStamp+data);
	   param.put("data", data);
	   param.put("Signature", Signature.toUpperCase());

	  /* String responsResult= PosHttpHelper.doPostWithUtf8(url, param);
		logger.info("导入订单-返回结果："+responsResult);*/
	  boolean isPos = false;
	  int posNo=0;
	  while(true){
   		//导入到pos的次数
			posNo++;
			String responsResult= PosHttpHelper.doPostWithUtf8(PosCommons.url, param);
			if(StringUtils.isNotBlank(responsResult)
					&&!responsResult.equalsIgnoreCase("fail")){
				PosResult1 orderResult=  JsonUtils.jsonToObject(PosResult1.class, responsResult);
				if(orderResult.ResCode.equals(0)){
					isPos=true;
				}
			}
			//最多导入五次。由于网络问题，可能会导致导入失败

			if(isPos||posNo>=5){
				break;
			}
			logger.info("订单导入，第"+posNo+"次导入"+":订单返回的POS返回结果＝"+responsResult);
		  //  System.out.println("订单返回的POS返回结果"+responsResult);
		} 
		//修改订单是否pos状态
		if(isPos){
			orderMapper.posOrder(order.getId());
		}
   }

}
